/*
 * @lc app=leetcode.cn id=875 lang=golang
 *
 * [875] 爱吃香蕉的珂珂
 */

// @lc code=start
func minEatingSpeed(piles []int, h int) int {
	left := 1
	right := 0
	// 初始化上下限，上限：最大堆，下限：1
	for _, pile := range piles {
		if pile > right {
			right = pile
		}
	}

	// 二分模板
	for left < right {
		mid := (left + right) / 2

		if isValid(piles, h, mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return right
}

// 二分答案：判断K是否合法
func isValid(piles []int, h, K int) bool {
	useHour := 0
	for _, pile := range piles {
		hour := pile / K
		if pile%K > 0 {
			hour += 1
		}
		useHour += hour
	}
	return useHour <= h
}

// @lc code=end

